package com.api.common.alert;

import com.api.common.alert.AlertManager;
import com.api.common.alert.AlertTypeConstants;
import com.api.common.alert.model.AlertLevel;
import com.api.common.alert.model.AlertMessage;

import com.api.common.alert.model.AlertTypeEnums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 通用告警辅助类
 * 提供各种场景的快捷告警方法
 */
@Component
@Slf4j
@ConditionalOnProperty(prefix = "alert", name = "enabled", havingValue = "true")
public class CommonAlertHelper {

    @Resource
    private AlertManager alertManager;

    /**
     * 发布告警事件
     */
    private void publish(AlertMessage event) {
        try {
            alertManager.process(event);
        } catch (Exception e) {
            log.error("告警发送失败", e);
        }
    }

    /**
     * 构建带邮箱指定的AlertMessage.Builder
     * 如果toEmail不为空，会自动设置notifierType为EMAIL
     */
    private AlertMessage.AlertMessageBuilder buildAlertWithEmail(AlertMessage.AlertMessageBuilder builder, String toEmail) {
        if (toEmail != null) {
            builder.notifierType(AlertTypeEnums.EMAIL).toEmail(toEmail);
        }
        return builder;
    }

    // ========================================
    // ========== API相关告警 ==========
    // ========================================

    /**
     * API 故障告警
     */
    public void apiFailure(String apiName, String reason, int failCount) {
        apiFailure(apiName, reason, failCount, null);
    }

    /**
     * API 故障告警（指定邮箱）
     */
    public void apiFailure(String apiName, String reason, int failCount, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.API_FAILURE)
                .level(AlertLevel.CRITICAL)
                .source(apiName)
                .message(String.format("API连续失败 | API=%s, 失败次数=%d, 原因=%s",
                        apiName, failCount, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("failCount", failCount);
                            put("reason", reason);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * API 响应慢告警
     */
    public void apiSlow(String apiName, long durationMs) {
        apiSlow(apiName, durationMs, null);
    }

    /**
     * API 响应慢告警（指定邮箱）
     */
    public void apiSlow(String apiName, long durationMs, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.API_SLOW)
                .level(AlertLevel.MEDIUM)
                .source(apiName)
                .message(String.format("API响应慢 | API=%s, 耗时=%dms", apiName, durationMs))
                .context( Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("durationMs", durationMs);

                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * API 超时告警
     */
    public void apiTimeout(String apiName, long timeoutMs) {
        apiTimeout(apiName, timeoutMs, null);
    }

    /**
     * API 超时告警（指定邮箱）
     */
    public void apiTimeout(String apiName, long timeoutMs, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.API_TIMEOUT)
                .level(AlertLevel.HIGH)
                .source(apiName)
                .message(String.format("API请求超时 | API=%s, 超时阈值=%dms", apiName, timeoutMs))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("timeoutMs", timeoutMs);

                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * API 限流告警
     */
    public void apiRateLimit(String apiName, String userId, int requestCount) {
        apiRateLimit(apiName, userId, requestCount, null);
    }

    /**
     * API 限流告警（指定邮箱）
     */
    public void apiRateLimit(String apiName, String userId, int requestCount, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.API_RATE_LIMIT)
                .level(AlertLevel.MEDIUM)
                .source(apiName)
                .message(String.format("API触发限流 | API=%s, 用户=%s, 请求数=%d",
                        apiName, userId, requestCount))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("userId", userId);
                            put("requestCount", requestCount);

                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    // ========================================
    // ========== 定时任务相关告警 ==========
    // ========================================

    /**
     * 任务执行失败告警
     */
    public void taskFailure(String taskName, String reason) {
        taskFailure(taskName, reason, null);
    }

    /**
     * 任务执行失败告警（指定邮箱）
     */
    public void taskFailure(String taskName, String reason, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.TASK_FAILURE)
                .level(AlertLevel.HIGH)
                .source(taskName)
                .message(String.format("任务执行失败 | 任务=%s, 原因=%s", taskName, reason))
                .context(Collections.singletonMap("reason", reason))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 任务执行超时告警
     */
    public void taskTimeout(String taskName, long durationMs) {
        taskTimeout(taskName, durationMs, null);
    }

    /**
     * 任务执行超时告警（指定邮箱）
     */
    public void taskTimeout(String taskName, long durationMs, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.TASK_TIMEOUT)
                .level(AlertLevel.HIGH)
                .source(taskName)
                .message(String.format("任务执行超时 | 任务=%s, 耗时=%dms", taskName, durationMs))
                .context(Collections.singletonMap("durationMs", durationMs))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 任务被跳过告警
     */
    public void taskSkipped(String taskName, String reason) {
        taskSkipped(taskName, reason, null);
    }

    /**
     * 任务被跳过告警（指定邮箱）
     */
    public void taskSkipped(String taskName, String reason, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.TASK_SKIPPED)
                .level(AlertLevel.MEDIUM)
                .source(taskName)
                .message(String.format("任务被跳过 | 任务=%s, 原因=%s", taskName, reason))
                .context(Collections.singletonMap("reason", reason))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    // ========================================
    // ========== 线程池相关告警 ==========
    // ========================================

    /**
     * 线程池饱和告警
     */
    public void threadPoolSaturated(String poolName, int activeCount, int maxPoolSize) {
        threadPoolSaturated(poolName, activeCount, maxPoolSize, null);
    }

    /**
     * 线程池饱和告警（指定邮箱）
     */
    public void threadPoolSaturated(String poolName, int activeCount, int maxPoolSize, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.THREADPOOL_SATURATED)
                .level(AlertLevel.CRITICAL)
                .source(poolName)
                .message(String.format("线程池即将饱和 | 线程池=%s, 活跃线程=%d/%d",
                        poolName, activeCount, maxPoolSize))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("activeCount", activeCount);
                            put("maxPoolSize", maxPoolSize);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 线程池队列积压告警
     */
    public void threadPoolQueueFull(String poolName, int queueSize, int queueCapacity) {
        threadPoolQueueFull(poolName, queueSize, queueCapacity, null);
    }

    /**
     * 线程池队列积压告警（指定邮箱）
     */
    public void threadPoolQueueFull(String poolName, int queueSize, int queueCapacity, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.THREADPOOL_QUEUE_FULL)
                .level(AlertLevel.HIGH)
                .source(poolName)
                .message(String.format("线程池队列积压 | 线程池=%s, 队列大小=%d/%d",
                        poolName, queueSize, queueCapacity))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("queueSize", queueSize);
                            put("queueCapacity", queueCapacity);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 线程池任务拒绝告警
     */
    public void threadPoolRejected(String poolName, int rejectedCount) {
        threadPoolRejected(poolName, rejectedCount, null);
    }

    /**
     * 线程池任务拒绝告警（指定邮箱）
     */
    public void threadPoolRejected(String poolName, int rejectedCount, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.THREADPOOL_REJECTED)
                .level(AlertLevel.CRITICAL)
                .source(poolName)
                .message(String.format("线程池任务被拒绝 | 线程池=%s, 拒绝数=%d",
                        poolName, rejectedCount))
                .context(Collections.singletonMap("rejectedCount", rejectedCount))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    // ========================================
    // ========== 数据库相关告警 ==========
    // ========================================

    /**
     * 数据库连接失败告警
     */
    public void databaseConnectionFailure(String datasource, String reason) {
        databaseConnectionFailure(datasource, reason, null);
    }

    /**
     * 数据库连接失败告警（指定邮箱）
     */
    public void databaseConnectionFailure(String datasource, String reason, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.DATABASE_CONNECTION_FAILURE)
                .level(AlertLevel.CRITICAL)
                .source(datasource)
                .message(String.format("数据库连接失败 | 数据源=%s, 原因=%s", datasource, reason))
                .context(Collections.singletonMap("reason", reason))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 慢查询告警
     */
    public void databaseSlowQuery(String sql, long durationMs) {
        databaseSlowQuery(sql, durationMs, null);
    }

    /**
     * 慢查询告警（指定邮箱）
     */
    public void databaseSlowQuery(String sql, long durationMs, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.DATABASE_SLOW_QUERY)
                .level(AlertLevel.MEDIUM)
                .source("Database")
                .message(String.format("慢查询检测 | 耗时=%dms, SQL=%s", durationMs, truncate(sql, 100)))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("durationMs", durationMs);
                            put("sql", truncate(sql, 500));
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 数据库死锁告警
     */
    public void databaseDeadlock(String tableName, String lockInfo) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.DATABASE_DEADLOCK)
                .level(AlertLevel.HIGH)
                .source("Database")
                .message(String.format("检测到死锁 | 表=%s", tableName))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("table", tableName);
                            put("lockInfo", lockInfo);
                        }}
                ))
                .build());
    }

    /**
     * 数据库连接池耗尽告警
     */
    public void databasePoolExhausted(String datasource, int activeConnections, int maxConnections) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.DATABASE_POOL_EXHAUSTED)
                .level(AlertLevel.CRITICAL)
                .source(datasource)
                .message(String.format("连接池耗尽 | 数据源=%s, 活跃连接=%d/%d",
                        datasource, activeConnections, maxConnections))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("activeConnections", activeConnections);
                            put("maxConnections", maxConnections);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== Redis缓存相关告警 ==========
    // ========================================

    /**
     * 缓存命中率低告警
     */
    public void cacheHitRateLow(String cacheName, double hitRate, double threshold) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.CACHE_HIT_RATE_LOW)
                .level(AlertLevel.MEDIUM)
                .source(cacheName)
                .message(String.format("缓存命中率低 | 缓存=%s, 命中率=%.2f%%, 阈值=%.2f%%",
                        cacheName, hitRate * 100, threshold * 100))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("hitRate", hitRate);
                            put("threshold", threshold);
                        }}
                ))
                .build());
    }

    /**
     * Redis连接失败告警
     */
    public void cacheConnectionFailure(String redisHost, String reason) {
        cacheConnectionFailure(redisHost, reason, null);
    }

    /**
     * Redis连接失败告警（指定邮箱）
     */
    public void cacheConnectionFailure(String redisHost, String reason, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.CACHE_CONNECTION_FAILURE)
                .level(AlertLevel.CRITICAL)
                .source("Redis")
                .message(String.format("Redis连接失败 | 主机=%s, 原因=%s", redisHost, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("host", redisHost);
                            put("reason", reason);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 缓存驱逐率高告警
     */
    public void cacheEvictionHigh(String cacheName, long evictionCount, long totalCount) {
        cacheEvictionHigh(cacheName, evictionCount, totalCount, null);
    }

    /**
     * 缓存驱逐率高告警（指定邮箱）
     */
    public void cacheEvictionHigh(String cacheName, long evictionCount, long totalCount, String toEmail) {
        double evictionRate = (double) evictionCount / totalCount * 100;
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.CACHE_EVICTION_HIGH)
                .level(AlertLevel.MEDIUM)
                .source(cacheName)
                .message(String.format("缓存驱逐率高 | 缓存=%s, 驱逐率=%.2f%%, 驱逐数=%d",
                        cacheName, evictionRate, evictionCount))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("evictionCount", evictionCount);
                            put("totalCount", totalCount);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * Redis内存使用率高告警
     */
    public void cacheMemoryHigh(long usedMemoryMb, long maxMemoryMb) {
        double usageRate = (double) usedMemoryMb / maxMemoryMb * 100;
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.CACHE_MEMORY_HIGH)
                .level(AlertLevel.HIGH)
                .source("Redis")
                .message(String.format("Redis内存使用率高 | 使用率=%.2f%%, 已用=%dMB/%dMB",
                        usageRate, usedMemoryMb, maxMemoryMb))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("usedMemoryMb", usedMemoryMb);
                            put("maxMemoryMb", maxMemoryMb);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== MQ消息队列相关告警 ==========
    // ========================================

    /**
     * MQ消息发送失败告警
     */
    public void mqSendFailure(String exchange, String routingKey, String reason, int retryCount) {
        mqSendFailure(exchange, routingKey, reason, retryCount, null);
    }

    /**
     * MQ消息发送失败告警（指定邮箱）
     */
    public void mqSendFailure(String exchange, String routingKey, String reason, int retryCount, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.MQ_SEND_FAILURE)
                .level(AlertLevel.HIGH)
                .source("RabbitMQ")
                .message(String.format("消息发送失败 | 交换机=%s, 路由=%s, 重试=%d次",
                        exchange, routingKey, retryCount))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("exchange", exchange);
                            put("routingKey", routingKey);
                            put("reason", reason);
                            put("retryCount", retryCount);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * MQ消息消费失败告警
     */
    public void mqConsumeFailure(String queue, String messageId, String reason) {
        mqConsumeFailure(queue, messageId, reason, null);
    }

    /**
     * MQ消息消费失败告警（指定邮箱）
     */
    public void mqConsumeFailure(String queue, String messageId, String reason, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.MQ_CONSUME_FAILURE)
                .level(AlertLevel.HIGH)
                .source("RabbitMQ")
                .message(String.format("消息消费失败 | 队列=%s, 消息ID=%s, 原因=%s",
                        queue, messageId, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("queue", queue);
                            put("messageId", messageId);
                            put("reason", reason);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * MQ队列积压告警
     */
    public void mqQueueBacklog(String queue, int messageCount, int threshold) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.MQ_QUEUE_BACKLOG)
                .level(AlertLevel.MEDIUM)
                .source("RabbitMQ")
                .message(String.format("队列消息积压 | 队列=%s, 积压数=%d, 阈值=%d",
                        queue, messageCount, threshold))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("queue", queue);
                            put("messageCount", messageCount);
                            put("threshold", threshold);
                        }}
                ))
                .build());
    }

    /**
     * 死信队列告警
     */
    public void mqDeadLetter(String queue, String messageId, String originalQueue) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.MQ_DEAD_LETTER)
                .level(AlertLevel.HIGH)
                .source("RabbitMQ")
                .message(String.format("消息进入死信队列 | 死信队列=%s, 原队列=%s, 消息ID=%s",
                        queue, originalQueue, messageId))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("queue", queue);
                            put("originalQueue", originalQueue);
                            put("messageId", messageId);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== Elasticsearch相关告警 ==========
    // ========================================

    /**
     * ES连接失败告警
     */
    public void esConnectionFailure(String clusterName, String nodes, String reason) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.ES_CONNECTION_FAILURE)
                .level(AlertLevel.CRITICAL)
                .source("Elasticsearch")
                .message(String.format("ES连接失败 | 集群=%s, 节点=%s, 原因=%s",
                        clusterName, nodes, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("cluster", clusterName);
                            put("nodes", nodes);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    /**
     * ES查询慢告警
     */
    public void esQuerySlow(String index, String query, long durationMs) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.ES_QUERY_SLOW)
                .level(AlertLevel.MEDIUM)
                .source("Elasticsearch")
                .message(String.format("ES查询慢 | 索引=%s, 耗时=%dms", index, durationMs))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("index", index);
                            put("durationMs", durationMs);
                            put("query", truncate(query, 200));
                        }}
                ))
                .build());
    }

    /**
     * ES索引失败告警
     */
    public void esIndexFailure(String index, String docId, String reason) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.ES_INDEX_FAILURE)
                .level(AlertLevel.HIGH)
                .source("Elasticsearch")
                .message(String.format("ES索引失败 | 索引=%s, 文档ID=%s, 原因=%s",
                        index, docId, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("index", index);
                            put("docId", docId);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    /**
     * ES同步延迟告警
     */
    public void esSyncDelay(String index, long delayMinutes) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.ES_SYNC_DELAY)
                .level(AlertLevel.MEDIUM)
                .source("Elasticsearch")
                .message(String.format("ES数据同步延迟 | 索引=%s, 延迟=%d分钟",
                        index, delayMinutes))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("index", index);
                            put("delayMinutes", delayMinutes);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 推荐系统相关告警 ==========
    // ========================================

    /**
     * 推荐模型重建失败告警
     */
    public void recommendModelRebuildFailure(String modelType, String reason) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.RECOMMEND_MODEL_REBUILD_FAILURE)
                .level(AlertLevel.HIGH)
                .source("RecommendSystem")
                .message(String.format("推荐模型重建失败 | 模型=%s, 原因=%s", modelType, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("modelType", modelType);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    /**
     * 推荐模型重建慢告警
     */
    public void recommendModelSlow(String modelType, long durationMs, int interfaceCount) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.RECOMMEND_MODEL_SLOW)
                .level(AlertLevel.MEDIUM)
                .source("RecommendSystem")
                .message(String.format("推荐模型重建耗时长 | 模型=%s, 耗时=%dms, 接口数=%d",
                        modelType, durationMs, interfaceCount))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("modelType", modelType);
                            put("durationMs", durationMs);
                            put("interfaceCount", interfaceCount);
                        }}
                ))
                .build());
    }

    /**
     * 推荐数据不足告警
     */
    public void recommendDataInsufficient(String dataType, int actualCount, int requiredCount) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.RECOMMEND_DATA_INSUFFICIENT)
                .level(AlertLevel.MEDIUM)
                .source("RecommendSystem")
                .message(String.format("推荐数据不足 | 数据类型=%s, 实际=%d, 需要=%d",
                        dataType, actualCount, requiredCount))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("dataType", dataType);
                            put("actualCount", actualCount);
                            put("requiredCount", requiredCount);
                        }}
                ))
                .build());
    }

    /**
     * 用户冷启动告警
     */
    public void recommendColdStart(long userId, String reason) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.RECOMMEND_COLD_START)
                .level(AlertLevel.INFO)
                .source("RecommendSystem")
                .message(String.format("用户冷启动 | 用户ID=%d, 原因=%s", userId, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("userId", userId);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 风控系统相关告警 ==========
    // ========================================

    /**
     * 风控模型失败告警
     */
    public void riskModelFailure(String modelName, String reason) {
        riskModelFailure(modelName, reason, null);
    }

    /**
     * 风控模型失败告警（指定邮箱）
     */
    public void riskModelFailure(String modelName, String reason, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.RISK_MODEL_FAILURE)
                .level(AlertLevel.CRITICAL)
                .source("RiskSystem")
                .message(String.format("风控模型失败 | 模型=%s, 原因=%s", modelName, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("modelName", modelName);
                            put("reason", reason);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 高风险评分告警
     */
    public void riskHighScore(long userId, String ip, double riskScore, String reason) {
        riskHighScore(userId, ip, riskScore, reason, null);
    }

    /**
     * 高风险评分告警（指定邮箱）
     */
    public void riskHighScore(long userId, String ip, double riskScore, String reason, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.RISK_HIGH_SCORE)
                .level(AlertLevel.HIGH)
                .source("RiskSystem")
                .message(String.format("检测到高风险行为 | 用户=%d, IP=%s, 风险分=%.2f",
                        userId, maskIp(ip), riskScore))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("userId", userId);
                            put("ip", maskIp(ip));
                            put("riskScore", riskScore);
                            put("reason", reason);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 风控拦截率过高告警
     */
    public void riskBlockRateHigh(double blockRate, int totalRequests, int blockedRequests) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.RISK_BLOCK_RATE_HIGH)
                .level(AlertLevel.MEDIUM)
                .source("RiskSystem")
                .message(String.format("风控拦截率过高 | 拦截率=%.2f%%, 总请求=%d, 拦截=%d",
                        blockRate * 100, totalRequests, blockedRequests))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("blockRate", blockRate);
                            put("totalRequests", totalRequests);
                            put("blockedRequests", blockedRequests);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 网关相关告警 ==========
    // ========================================

    /**
     * 网关路由失败告警
     */
    public void gatewayRouteFailure(String routeId, String targetUri, String reason) {
        gatewayRouteFailure(routeId, targetUri, reason, null);
    }

    /**
     * 网关路由失败告警（指定邮箱）
     */
    public void gatewayRouteFailure(String routeId, String targetUri, String reason, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.GATEWAY_ROUTE_FAILURE)
                .level(AlertLevel.HIGH)
                .source("Gateway")
                .message(String.format("网关路由失败 | 路由ID=%s, 目标=%s, 原因=%s",
                        routeId, targetUri, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("routeId", routeId);
                            put("targetUri", targetUri);
                            put("reason", reason);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 熔断器打开告警
     */
    public void gatewayCircuitBreakerOpen(String serviceName, double failureRate) {
        gatewayCircuitBreakerOpen(serviceName, failureRate, null);
    }

    /**
     * 熔断器打开告警（指定邮箱）
     */
    public void gatewayCircuitBreakerOpen(String serviceName, double failureRate, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.GATEWAY_CIRCUIT_BREAKER_OPEN)
                .level(AlertLevel.CRITICAL)
                .source("Gateway")
                .message(String.format("熔断器已打开 | 服务=%s, 失败率=%.2f%%",
                        serviceName, failureRate * 100))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("serviceName", serviceName);
                            put("failureRate", failureRate);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 上游服务不可用告警
     */
    public void gatewayUpstreamUnavailable(String serviceName, String instanceList) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.GATEWAY_UPSTREAM_UNAVAILABLE)
                .level(AlertLevel.CRITICAL)
                .source("Gateway")
                .message(String.format("上游服务不可用 | 服务=%s, 实例=%s",
                        serviceName, instanceList))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("serviceName", serviceName);
                            put("instances", instanceList);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 限流相关告警 ==========
    // ========================================

    /**
     * 限流触发告警
     */
    public void rateLimitTriggered(String resource, String userId, int requestCount, int limit) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.RATE_LIMIT_TRIGGERED)
                .level(AlertLevel.MEDIUM)
                .source("RateLimiter")
                .message(String.format("触发限流 | 资源=%s, 用户=%s, 请求数=%d, 限制=%d",
                        resource, userId, requestCount, limit))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("resource", resource);
                            put("userId", userId);
                            put("requestCount", requestCount);
                            put("limit", limit);
                        }}
                ))
                .build());
    }

    /**
     * 突发流量告警
     */
    public void rateLimitBurst(String resource, int currentQps, int normalQps) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.RATE_LIMIT_BURST)
                .level(AlertLevel.HIGH)
                .source("RateLimiter")
                .message(String.format("检测到突发流量 | 资源=%s, 当前QPS=%d, 正常QPS=%d",
                        resource, currentQps, normalQps))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("resource", resource);
                            put("currentQps", currentQps);
                            put("normalQps", normalQps);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 数据同步相关告警 ==========
    // ========================================

    /**
     * Canal同步失败告警
     */
    public void canalSyncFailure(String destination, String database, String table, String reason) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.CANAL_SYNC_FAILURE)
                .level(AlertLevel.HIGH)
                .source("Canal")
                .message(String.format("Canal同步失败 | 实例=%s, 库表=%s.%s, 原因=%s",
                        destination, database, table, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("destination", destination);
                            put("database", database);
                            put("table", table);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    /**
     * Canal连接丢失告警
     */
    public void canalConnectionLost(String destination, int retryCount) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.CANAL_CONNECTION_LOST)
                .level(AlertLevel.CRITICAL)
                .source("Canal")
                .message(String.format("Canal连接丢失 | 实例=%s, 重试次数=%d",
                        destination, retryCount))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("destination", destination);
                            put("retryCount", retryCount);
                        }}
                ))
                .build());
    }

    /**
     * 数据不一致告警
     */
    public void dataInconsistency(String dataType, String sourceId, String targetId, String detail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.DATA_INCONSISTENCY)
                .level(AlertLevel.HIGH)
                .source("DataSync")
                .message(String.format("数据不一致 | 类型=%s, 源ID=%s, 目标ID=%s",
                        dataType, sourceId, targetId))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("dataType", dataType);
                            put("sourceId", sourceId);
                            put("targetId", targetId);
                            put("detail", detail);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 系统资源相关告警 ==========
    // ========================================

    /**
     * 内存使用率高告警
     */
    public void memoryHigh(long usedMemoryMb, long maxMemoryMb, double usageRate) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.MEMORY_HIGH)
                .level(AlertLevel.HIGH)
                .source("System")
                .message(String.format("内存使用率高 | 使用率=%.2f%%, 已用=%dMB/%dMB",
                        usageRate * 100, usedMemoryMb, maxMemoryMb))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("usedMemoryMb", usedMemoryMb);
                            put("maxMemoryMb", maxMemoryMb);
                            put("usageRate", usageRate);
                        }}
                ))
                .build());
    }

    /**
     * CPU使用率高告警
     */
    public void cpuHigh(double cpuUsage) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.CPU_HIGH)
                .level(AlertLevel.HIGH)
                .source("System")
                .message(String.format("CPU使用率高 | CPU=%.2f%%", cpuUsage * 100))
                .context(Collections.singletonMap("cpuUsage", cpuUsage))
                .build());
    }

    /**
     * 磁盘空间不足告警
     */
    public void diskSpaceLow(String partition, long availableMb, long totalMb) {
        double usageRate = (double) (totalMb - availableMb) / totalMb * 100;
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.DISK_SPACE_LOW)
                .level(AlertLevel.HIGH)
                .source("System")
                .message(String.format("磁盘空间不足 | 分区=%s, 使用率=%.2f%%, 可用=%dMB/%dMB",
                        partition, usageRate, availableMb, totalMb))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("partition", partition);
                            put("availableMb", availableMb);
                            put("totalMb", totalMb);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 业务相关告警 ==========
    // ========================================

    /**
     * 数据清理失败告警
     */
    public void cleanupFailure(String dataType, String reason) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.CLEANUP_FAILURE)
                .level(AlertLevel.MEDIUM)
                .source("DataCleanup")
                .message(String.format("数据清理失败 | 类型=%s, 原因=%s", dataType, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("dataType", dataType);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    /**
     * 数据聚合失败告警
     */
    public void aggregationFailure(String aggregationType, String reason) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.AGGREGATION_FAILURE)
                .level(AlertLevel.MEDIUM)
                .source("DataAggregation")
                .message(String.format("数据聚合失败 | 类型=%s, 原因=%s", aggregationType, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("aggregationType", aggregationType);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    /**
     * 数据归档失败告警
     */
    public void archiveFailure(String dataType, String period, String reason) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.ARCHIVE_FAILURE)
                .level(AlertLevel.MEDIUM)
                .source("DataArchive")
                .message(String.format("数据归档失败 | 类型=%s, 周期=%s, 原因=%s",
                        dataType, period, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("dataType", dataType);
                            put("period", period);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    /**
     * 配置重载失败告警
     */
    public void configReloadFailure(String configName, String reason) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.CONFIG_RELOAD_FAILURE)
                .level(AlertLevel.HIGH)
                .source("ConfigManager")
                .message(String.format("配置重载失败 | 配置=%s, 原因=%s", configName, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("configName", configName);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 工具方法 ==========
    // ========================================

    /**
     * 截断字符串
     */
    private String truncate(String text, int maxLength) {
        if (text == null || text.length() <= maxLength) {
            return text;
        }
        return text.substring(0, maxLength) + "...";
    }

    /**
     * IP脱敏
     */
    private String maskIp(String ip) {
        if (ip == null || ip.isEmpty()) {
            return "unknown";
        }
        String[] parts = ip.split("\\.");
        if (parts.length == 4) {
            return parts[0] + "." + parts[1] + ".*.*";
        }
        return "***";
    }

    // ========================================
    // ========== 用户业务相关告警 ==========
    // ========================================

    /**
     * 用户登录失败告警
     */
    public void userLoginFailure(long userId, String username, String reason, int failCount) {
        userLoginFailure(userId, username, reason, failCount, null);
    }

    /**
     * 用户登录失败告警（指定邮箱）
     */
    public void userLoginFailure(long userId, String username, String reason, int failCount, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.USER_LOGIN_FAILURE)
                .level(failCount >= 5 ? AlertLevel.HIGH : AlertLevel.MEDIUM)
                .source("UserService")
                .message(String.format("用户登录失败 | 用户=%s, 失败次数=%d, 原因=%s",
                        username, failCount, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("userId", userId);
                            put("username", username);
                            put("failCount", failCount);
                            put("reason", reason);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 用户注册失败告警
     */
    public void userRegisterFailure(String username, String reason) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.USER_REGISTER_FAILURE)
                .level(AlertLevel.MEDIUM)
                .source("UserService")
                .message(String.format("用户注册失败 | 用户名=%s, 原因=%s", username, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("username", username);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    /**
     * 用户账户被锁定告警
     */
    public void userAccountLocked(long userId, String username, String reason) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.USER_ACCOUNT_LOCKED)
                .level(AlertLevel.HIGH)
                .source("UserService")
                .message(String.format("用户账户被锁定 | 用户=%s(ID=%d), 原因=%s",
                        username, userId, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("userId", userId);
                            put("username", username);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    /**
     * 用户异常行为告警
     */
    public void userAbnormalBehavior(long userId, String behavior, String detail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.USER_ABNORMAL_BEHAVIOR)
                .level(AlertLevel.HIGH)
                .source("UserService")
                .message(String.format("检测到用户异常行为 | 用户ID=%d, 行为=%s",
                        userId, behavior))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("userId", userId);
                            put("behavior", behavior);
                            put("detail", detail);
                        }}
                ))
                .build());
    }

    /**
     * 用户活跃度下降告警
     */
    public void userActiveDrop(int activeUsers, int previousUsers, double dropRate) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.USER_ACTIVE_DROP)
                .level(AlertLevel.MEDIUM)
                .source("UserService")
                .message(String.format("用户活跃度下降 | 当前=%d, 之前=%d, 下降=%.2f%%",
                        activeUsers, previousUsers, dropRate * 100))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("activeUsers", activeUsers);
                            put("previousUsers", previousUsers);
                            put("dropRate", dropRate);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 接口调用业务相关告警 ==========
    // ========================================

    /**
     * 接口调用次数耗尽告警
     */
    public void interfaceQuotaExhausted(long userId, long interfaceId, String interfaceName, int totalCalls) {
        interfaceQuotaExhausted(userId, interfaceId, interfaceName, totalCalls, null);
    }

    /**
     * 接口调用次数耗尽告警（指定邮箱）
     */
    public void interfaceQuotaExhausted(long userId, long interfaceId, String interfaceName, int totalCalls, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.INTERFACE_QUOTA_EXHAUSTED)
                .level(AlertLevel.MEDIUM)
                .source("InterfaceService")
                .message(String.format("接口调用次数耗尽 | 用户=%d, 接口=%s, 已调用=%d次",
                        userId, interfaceName, totalCalls))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("userId", userId);
                            put("interfaceId", interfaceId);
                            put("interfaceName", interfaceName);
                            put("totalCalls", totalCalls);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 接口下线告警
     */
    public void interfaceOffline(long interfaceId, String interfaceName, String reason) {
        interfaceOffline(interfaceId, interfaceName, reason, null);
    }

    /**
     * 接口下线告警（指定邮箱）
     */
    public void interfaceOffline(long interfaceId, String interfaceName, String reason, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.INTERFACE_OFFLINE)
                .level(AlertLevel.CRITICAL)
                .source("InterfaceService")
                .message(String.format("接口已下线 | 接口=%s(ID=%d), 原因=%s",
                        interfaceName, interfaceId, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("interfaceId", interfaceId);
                            put("interfaceName", interfaceName);
                            put("reason", reason);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 接口权限不足告警
     */
    public void interfacePermissionDenied(long userId, long interfaceId, String interfaceName) {
        interfacePermissionDenied(userId, interfaceId, interfaceName, null);
    }

    /**
     * 接口权限不足告警（指定邮箱）
     */
    public void interfacePermissionDenied(long userId, long interfaceId, String interfaceName, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.INTERFACE_PERMISSION_DENIED)
                .level(AlertLevel.MEDIUM)
                .source("InterfaceService")
                .message(String.format("接口权限不足 | 用户=%d, 接口=%s",
                        userId, interfaceName))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("userId", userId);
                            put("interfaceId", interfaceId);
                            put("interfaceName", interfaceName);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 接口调用激增告警
     */
    public void interfaceCallSpike(long interfaceId, String interfaceName, int currentQps, int normalQps) {
        interfaceCallSpike(interfaceId, interfaceName, currentQps, normalQps, null);
    }

    /**
     * 接口调用激增告警（指定邮箱）
     */
    public void interfaceCallSpike(long interfaceId, String interfaceName, int currentQps, int normalQps, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.INTERFACE_CALL_SPIKE)
                .level(AlertLevel.HIGH)
                .source("InterfaceService")
                .message(String.format("接口调用激增 | 接口=%s, 当前QPS=%d, 正常QPS=%d",
                        interfaceName, currentQps, normalQps))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("interfaceId", interfaceId);
                            put("interfaceName", interfaceName);
                            put("currentQps", currentQps);
                            put("normalQps", normalQps);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 接口错误率高告警
     */
    public void interfaceErrorRateHigh(long interfaceId, String interfaceName, double errorRate, int totalCalls, int errorCalls) {
        interfaceErrorRateHigh(interfaceId, interfaceName, errorRate, totalCalls, errorCalls, null);
    }

    /**
     * 接口错误率高告警（指定邮箱）
     */
    public void interfaceErrorRateHigh(long interfaceId, String interfaceName, double errorRate, int totalCalls, int errorCalls, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.INTERFACE_ERROR_RATE_HIGH)
                .level(AlertLevel.HIGH)
                .source("InterfaceService")
                .message(String.format("接口错误率高 | 接口=%s, 错误率=%.2f%%, 失败=%d/%d",
                        interfaceName, errorRate * 100, errorCalls, totalCalls))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("interfaceId", interfaceId);
                            put("interfaceName", interfaceName);
                            put("errorRate", errorRate);
                            put("totalCalls", totalCalls);
                            put("errorCalls", errorCalls);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    // ========================================
    // ========== 支付订单业务相关告警 ==========
    // ========================================

    /**
     * 支付失败告警
     */
    public void paymentFailure(String orderId, long userId, double amount, String reason) {
        paymentFailure(orderId, userId, amount, reason, null);
    }

    /**
     * 支付失败告警（指定邮箱）
     */
    public void paymentFailure(String orderId, long userId, double amount, String reason, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.PAYMENT_FAILURE)
                .level(AlertLevel.HIGH)
                .source("PaymentService")
                .message(String.format("支付失败 | 订单=%s, 用户=%d, 金额=%.2f, 原因=%s",
                        orderId, userId, amount, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("orderId", orderId);
                            put("userId", userId);
                            put("amount", amount);
                            put("reason", reason);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 支付超时告警
     */
    public void paymentTimeout(String orderId, long userId, double amount, long timeoutMs) {
        paymentTimeout(orderId, userId, amount, timeoutMs, null);
    }

    /**
     * 支付超时告警（指定邮箱）
     */
    public void paymentTimeout(String orderId, long userId, double amount, long timeoutMs, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.PAYMENT_TIMEOUT)
                .level(AlertLevel.MEDIUM)
                .source("PaymentService")
                .message(String.format("支付超时 | 订单=%s, 用户=%d, 金额=%.2f, 超时=%dms",
                        orderId, userId, amount, timeoutMs))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("orderId", orderId);
                            put("userId", userId);
                            put("amount", amount);
                            put("timeoutMs", timeoutMs);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 订单创建失败告警
     */
    public void orderCreationFailure(long userId, String productName, String reason) {
        orderCreationFailure(userId, productName, reason, null);
    }

    /**
     * 订单创建失败告警（指定邮箱）
     */
    public void orderCreationFailure(long userId, String productName, String reason, String toEmail) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.ORDER_CREATION_FAILURE)
                .level(AlertLevel.MEDIUM)
                .source("OrderService")
                .message(String.format("订单创建失败 | 用户=%d, 商品=%s, 原因=%s",
                        userId, productName, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("userId", userId);
                            put("productName", productName);
                            put("reason", reason);
                        }}
                ))
                .notifierType(toEmail != null ? AlertTypeEnums.EMAIL : null)
                .toEmail(toEmail)
                .build());
    }

    /**
     * 订单取消率高告警
     */
    public void orderCancelRateHigh(double cancelRate, int totalOrders, int canceledOrders) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.ORDER_CANCEL_RATE_HIGH)
                .level(AlertLevel.MEDIUM)
                .source("OrderService")
                .message(String.format("订单取消率高 | 取消率=%.2f%%, 取消数=%d/%d",
                        cancelRate * 100, canceledOrders, totalOrders))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("cancelRate", cancelRate);
                            put("totalOrders", totalOrders);
                            put("canceledOrders", canceledOrders);
                        }}
                ))
                .build());
    }

    /**
     * 退款失败告警
     */
    public void refundFailure(String orderId, long userId, double amount, String reason) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.REFUND_FAILURE)
                .level(AlertLevel.HIGH)
                .source("PaymentService")
                .message(String.format("退款失败 | 订单=%s, 用户=%d, 金额=%.2f, 原因=%s",
                        orderId, userId, amount, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("orderId", orderId);
                            put("userId", userId);
                            put("amount", amount);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 数据验证业务相关告警 ==========
    // ========================================

    /**
     * 数据校验失败告警
     */
    public void dataValidationFailure(String dataType, String fieldName, String value, String rule) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.DATA_VALIDATION_FAILURE)
                .level(AlertLevel.MEDIUM)
                .source("DataValidation")
                .message(String.format("数据校验失败 | 类型=%s, 字段=%s, 规则=%s",
                        dataType, fieldName, rule))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("dataType", dataType);
                            put("fieldName", fieldName);
                            put("value", truncate(value, 100));
                            put("rule", rule);
                        }}
                ))
                .build());
    }

    /**
     * 数据格式错误告警
     */
    public void dataFormatError(String dataType, String expectedFormat, String actualFormat) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.DATA_FORMAT_ERROR)
                .level(AlertLevel.MEDIUM)
                .source("DataValidation")
                .message(String.format("数据格式错误 | 类型=%s, 期望=%s, 实际=%s",
                        dataType, expectedFormat, actualFormat))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("dataType", dataType);
                            put("expectedFormat", expectedFormat);
                            put("actualFormat", actualFormat);
                        }}
                ))
                .build());
    }

    /**
     * 数据重复告警
     */
    public void dataDuplication(String dataType, String key, String value) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.DATA_DUPLICATION)
                .level(AlertLevel.MEDIUM)
                .source("DataValidation")
                .message(String.format("数据重复 | 类型=%s, 键=%s, 值=%s",
                        dataType, key, truncate(value, 50)))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("dataType", dataType);
                            put("key", key);
                            put("value", truncate(value, 100));
                        }}
                ))
                .build());
    }

    /**
     * 非法参数告警
     */
    public void illegalParameter(String method, String paramName, String paramValue, String reason) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.ILLEGAL_PARAMETER)
                .level(AlertLevel.MEDIUM)
                .source("ParameterValidation")
                .message(String.format("非法参数 | 方法=%s, 参数=%s, 原因=%s",
                        method, paramName, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("method", method);
                            put("paramName", paramName);
                            put("paramValue", truncate(paramValue, 100));
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 第三方服务相关告警 ==========
    // ========================================

    /**
     * 第三方API失败告警
     */
    public void thirdPartyApiFailure(String serviceName, String apiName, String reason, int retryCount) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.THIRD_PARTY_API_FAILURE)
                .level(AlertLevel.HIGH)
                .source("ThirdPartyService")
                .message(String.format("第三方API失败 | 服务=%s, API=%s, 重试=%d次, 原因=%s",
                        serviceName, apiName, retryCount, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("serviceName", serviceName);
                            put("apiName", apiName);
                            put("retryCount", retryCount);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    /**
     * 第三方服务超时告警
     */
    public void thirdPartyTimeout(String serviceName, String apiName, long durationMs, long timeoutMs) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.THIRD_PARTY_TIMEOUT)
                .level(AlertLevel.MEDIUM)
                .source("ThirdPartyService")
                .message(String.format("第三方服务超时 | 服务=%s, API=%s, 耗时=%dms, 超时阈值=%dms",
                        serviceName, apiName, durationMs, timeoutMs))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("serviceName", serviceName);
                            put("apiName", apiName);
                            put("durationMs", durationMs);
                            put("timeoutMs", timeoutMs);
                        }}
                ))
                .build());
    }

    /**
     * 第三方服务限流告警
     */
    public void thirdPartyRateLimited(String serviceName, String apiName, int requestCount) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.THIRD_PARTY_RATE_LIMITED)
                .level(AlertLevel.MEDIUM)
                .source("ThirdPartyService")
                .message(String.format("第三方服务限流 | 服务=%s, API=%s, 请求数=%d",
                        serviceName, apiName, requestCount))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("serviceName", serviceName);
                            put("apiName", apiName);
                            put("requestCount", requestCount);
                        }}
                ))
                .build());
    }

    /**
     * 短信发送失败告警
     */
    public void smsSendFailure(String phone, String reason, int retryCount) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.SMS_SEND_FAILURE)
                .level(AlertLevel.MEDIUM)
                .source("SmsService")
                .message(String.format("短信发送失败 | 手机=%s, 重试=%d次, 原因=%s",
                        maskPhone(phone), retryCount, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("phone", maskPhone(phone));
                            put("retryCount", retryCount);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    /**
     * 邮件发送失败告警
     */
    public void emailSendFailure(String email, String reason, int retryCount) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.EMAIL_SEND_FAILURE)
                .level(AlertLevel.MEDIUM)
                .source("EmailService")
                .message(String.format("邮件发送失败 | 邮箱=%s, 重试=%d次, 原因=%s",
                        maskEmail(email), retryCount, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("email", maskEmail(email));
                            put("retryCount", retryCount);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 审计安全相关告警 ==========
    // ========================================

    /**
     * 敏感操作告警
     */
    public void sensitiveOperation(long userId, String username, String operation, String target) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.SENSITIVE_OPERATION)
                .level(AlertLevel.HIGH)
                .source("AuditService")
                .message(String.format("敏感操作 | 用户=%s(ID=%d), 操作=%s, 目标=%s",
                        username, userId, operation, target))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("userId", userId);
                            put("username", username);
                            put("operation", operation);
                            put("target", target);
                        }}
                ))
                .build());
    }

    /**
     * 未授权访问告警
     */
    public void unauthorizedAccess(long userId, String resource, String ip) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.UNAUTHORIZED_ACCESS)
                .level(AlertLevel.HIGH)
                .source("SecurityService")
                .message(String.format("未授权访问 | 用户=%d, 资源=%s, IP=%s",
                        userId, resource, maskIp(ip)))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("userId", userId);
                            put("resource", resource);
                            put("ip", maskIp(ip));
                        }}
                ))
                .build());
    }

    /**
     * 可疑IP告警
     */
    public void suspiciousIp(String ip, String reason, int requestCount) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.SUSPICIOUS_IP)
                .level(AlertLevel.HIGH)
                .source("SecurityService")
                .message(String.format("可疑IP检测 | IP=%s, 请求数=%d, 原因=%s",
                        maskIp(ip), requestCount, reason))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("ip", maskIp(ip));
                            put("requestCount", requestCount);
                            put("reason", reason);
                        }}
                ))
                .build());
    }

    /**
     * 大量数据导出告警
     */
    public void dataExportLarge(long userId, String dataType, int recordCount, int threshold) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.DATA_EXPORT_LARGE)
                .level(AlertLevel.MEDIUM)
                .source("AuditService")
                .message(String.format("大量数据导出 | 用户=%d, 数据类型=%s, 导出数=%d, 阈值=%d",
                        userId, dataType, recordCount, threshold))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("userId", userId);
                            put("dataType", dataType);
                            put("recordCount", recordCount);
                            put("threshold", threshold);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 业务指标异常告警 ==========
    // ========================================

    /**
     * 业务指标异常告警
     */
    public void metricAnomaly(String metricName, double currentValue, double expectedValue, double deviation) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.METRIC_ANOMALY)
                .level(AlertLevel.MEDIUM)
                .source("MetricMonitor")
                .message(String.format("业务指标异常 | 指标=%s, 当前值=%.2f, 期望值=%.2f, 偏差=%.2f%%",
                        metricName, currentValue, expectedValue, deviation * 100))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("metricName", metricName);
                            put("currentValue", currentValue);
                            put("expectedValue", expectedValue);
                            put("deviation", deviation);
                        }}
                ))
                .build());
    }

    /**
     * 转化率下降告警
     */
    public void conversionRateDrop(String conversionType, double currentRate, double previousRate, double dropRate) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.CONVERSION_RATE_DROP)
                .level(AlertLevel.MEDIUM)
                .source("MetricMonitor")
                .message(String.format("转化率下降 | 类型=%s, 当前=%.2f%%, 之前=%.2f%%, 下降=%.2f%%",
                        conversionType, currentRate * 100, previousRate * 100, dropRate * 100))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("conversionType", conversionType);
                            put("currentRate", currentRate);
                            put("previousRate", previousRate);
                            put("dropRate", dropRate);
                        }}
                ))
                .build());
    }

    /**
     * 成功率下降告警
     */
    public void successRateDrop(String businessType, double currentRate, double previousRate, int totalCalls) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.SUCCESS_RATE_DROP)
                .level(AlertLevel.HIGH)
                .source("MetricMonitor")
                .message(String.format("成功率下降 | 业务=%s, 当前=%.2f%%, 之前=%.2f%%, 总次数=%d",
                        businessType, currentRate * 100, previousRate * 100, totalCalls))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("businessType", businessType);
                            put("currentRate", currentRate);
                            put("previousRate", previousRate);
                            put("totalCalls", totalCalls);
                        }}
                ))
                .build());
    }

    /**
     * 流量异常告警
     */
    public void trafficAnomaly(String trafficType, int currentValue, int normalValue, String trend) {
        publish(AlertMessage.builder()
                .alertType(AlertTypeConstants.TRAFFIC_ANOMALY)
                .level(AlertLevel.MEDIUM)
                .source("MetricMonitor")
                .message(String.format("流量异常 | 类型=%s, 当前=%d, 正常=%d, 趋势=%s",
                        trafficType, currentValue, normalValue, trend))
                .context(Collections.unmodifiableMap(
                        new HashMap<String, Object>() {{
                            put("trafficType", trafficType);
                            put("currentValue", currentValue);
                            put("normalValue", normalValue);
                            put("trend", trend);
                        }}
                ))
                .build());
    }

    // ========================================
    // ========== 工具方法（新增） ==========
    // ========================================

    /**
     * 手机号脱敏
     */
    private String maskPhone(String phone) {
        if (phone == null || phone.length() < 11) {
            return "***";
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }

    /**
     * 邮箱脱敏
     */
    private String maskEmail(String email) {
        if (email == null || !email.contains("@")) {
            return "***";
        }
        String[] parts = email.split("@");
        String username = parts[0];
        if (username.length() <= 2) {
            return "*@" + parts[1];
        }
        return username.substring(0, 2) + "***@" + parts[1];
    }
}